<template>
  <el-form :inline="true" class="demo-form-inline">
    <el-form-item label="价格">
      <el-input v-model="price" placeholder="请出价"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onplay">竞价</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  import axios from 'axios'
  export default {
    name: 'Work3',
    data() {
      return {
        websock: null,
        price: ''
      }
    },
    created() {
      this.initWebSocket()
    },

    methods: {
      //初始化连接
      initWebSocket: function() {
        //初始化WebSocket
        let url = 'ws://127.0.0.1:8087/webSocket/' + this.$cookies.get('account')
        this.websock = new WebSocket(url);

        //连接成功
        this.websock.onopen = () => {
          console.log("WebSocket连接成功");
        }

        //连接错误
        this.websock.onerror = () => {
          console.log("WebSocket连接发生错误");
          this.reconnect();
        }

        //监听后端传来的消息
        this.websock.onmessage = () => {
          console.log('监听关闭' + e)
          console.log("-----接收消息-------", e.data);
          var data = eval("(" + e.data + ")"); //解析对象
        }

        //关闭连接
        this.websock.onclose = () => {
          console.log("connection closed");
        }

      },

      //向后端发送数据
      websocketSend(text) { // 数据发送
        try {
          this.websock.send(text);
        } catch (err) {
          console.log("send failed (" + err.code + ")");
        }
      },
      //重连
      reconnect() {
        var that = this;
        if (that.lockReconnect) return;
        that.lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        setTimeout(function() {
          console.info("尝试重连...");
          that.initWebSocket();
          that.lockReconnect = false;
        }, 5000);
      },
      onplay() {

      }

    },

  }
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
